package com.sumainfor.wx.tenant.service.impl;


import com.sumainfor.common.Constants;
import com.sumainfor.common.util.ContextUtils;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.common.utlis.ComUtils;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.common.wechat.MapUtil;
import com.sumainfor.wx.tenant.dao.TenantCouponsMapper;
import com.sumainfor.wx.tenant.dao.UtilsMapper;
import com.sumainfor.wx.tenant.feign.DevelopmentFeignClient;
import com.sumainfor.wx.tenant.service.TenantCouponsService;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author PuaChen
 * @since 2019-01-28
 */
@Service
public class TenantCouponsServiceImpl implements TenantCouponsService {

    private ReentrantLock lock = new ReentrantLock(false);
    Logger log = LoggerFactory.getLogger(TenantCouponsServiceImpl.class);

    @Autowired
    private TenantCouponsMapper tenantCouponsMapper;

    @Autowired
    DevelopmentFeignClient couponFeignClient;

    @Autowired
    UtilsMapper utilsMapper;

    /**
     * <p>
     * 根据租客编号获取优惠券数量
     * </p>
     *
     * @author: zhoucong
     * @since:
     */
    @Override

      public Integer getTenantCouponsByTenIdCount(Map<String,Object>params) {

        return tenantCouponsMapper.getTenantCouponsByTenIdCount(params);
    }

    /**
     * <p>
     * 根据租客编号获取优惠券详情
     * </p>
     *
     * @author: zhoucong
     * @since:
     */
    @Override
    public List<Map<String, Object>> getTenantCouponsByTenId(Map<String, Object> params) {

        return tenantCouponsMapper.getTenantCouponsByTenId(params);
    }

    /**
     * <p>
     * 根据优惠券编码兑换优惠券1
     * </p>
     *
     * @author: zhoucong
     * @since: 2019-03-27
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public JsonResult getCouponByCouId(Map<String, Object> params) {

        JsonResult result = new JsonResult();
        /**
         * 加锁操作
         */
        lock.lock();
        try {
            JsonResult paraResult = couponFeignClient.getCouponByCouId(params);
            List<Map<String,Object>> paralist = (List<Map<String, Object>>) paraResult.get("result");
            System.out.println("paraList"+paralist);
            if (null == paralist ||paralist.size() == 0 ){
                result.putFailed("请输入正确的优惠券编码");
            }else{
                for (Map<String,Object> para: paralist) {
                    Integer sts = MapUtils.getInteger(para,"Status");
                    System.out.println("测试优惠券状态"+sts);
                    if (sts !=null&& sts ==1 ){
                        result.putFailed("优惠券已被领取");
                    }else{
                        log.info("111111111111111"+MapUtils.getInteger(para,"DateResult"));
                        if(MapUtils.getInteger(para,"DateResult")==0){
                            result.putFailed("优惠券已过期");
                        }else if (MapUtils.getInteger(para,"DateResult")==1){
                            result.putFailed("优惠券未到领取时间");
                        }else{
                            log.info("增加操作");
                            para.put("Validity",para.get("FianallyTime"));
                            para.put("Facevalue", para.get("CouPrice"));


                            para.put("TenId",MapUtils.getString(params,"TenId"));



                            para.put("term", "1");//创建端  1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
                            para.put("fnc",
                                    this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                            ParamsCommon.commonInsertParms(para);
                            String UUID;
                            Map<String,Object>uuid=utilsMapper.getUUID(new HashMap<String,Object>(){{
                                put("uuid", "Coucode");
                                put("database", Constants.DATA_SOURCE_TCTEN);
                                put("surface", "tcten_tenant_coupons");
                            }});
                            if(uuid!=null){
                                int number=Integer.valueOf(uuid.get("uuid").toString());
                                UUID= ComUtils.getLocalTrmSeqNum("YHJ",number);
                            }else{
                                UUID=ComUtils.getLocalTrmSeqNum("YHJ",0);
                            }
                            para.put("Coucode",UUID);
                            if (tenantCouponsMapper.insertTenantCoupons(para) > 0) {
                                result.putSuccess("兑换优惠券成功");
                                log.info("修改操作");
                                para.remove("Status");
                                para.put("Status","1");//更新优惠券是否核销 0 否 1 是
                                para.put("TenId",MapUtils.getString(params,"TenId"));
                                para.put("term", "1");// 更新端 Update端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                                para.put("fnc",
                                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名

                                ParamsCommon.commonUpdateParms(para);
                                System.out.println("updateParam"+para);
                                couponFeignClient.updateCouponStatus(para);
                            }
                            else {
                                result.putFailed("兑换优惠券失败");
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//事物回滚
            result.putFailed("服务器繁忙...");
        } finally {
            lock.unlock();
        }
        return result;
    }
}


